package com.wits.av;

import java.io.Closeable;
import java.io.IOException;

/**
 * Created by zhengboyuan on 2018-08-27.
 */

public class RtpSound implements Closeable {

    static boolean inited = false;

    public static void init() {
        JniRtpSound.rtpsound_init();
        inited = true;
    }

    public static void quit() {
        JniRtpSound.rtpsound_quit();
        inited = false;
    }

    protected int handle = JniRtpSound.INVALID_HANDLE;

    public RtpSound() {
        if (!inited) {
            init();
        }
    }

    @Override
    protected void finalize() {
        try {
            close();
        } catch (Throwable throwable) {
            //
        }
    }

    /**
     * 打开rtp播放器
     * @param port  本地传输端口
     * @param codec     音频编码
     * @param channels  音频通道数
     * @param samplerate    音频采样率
     * @return  true 表示成功.
     */
    public boolean open(int port, int codec, int channels, int samplerate) {
        try {
            close();
        } catch (Throwable throwable) {
            //
        }

        handle = JniRtpSound.rtpsound_open(port, codec, channels, samplerate);
        return isOpen();
    }

    @Override
    public void close() throws IOException {
        if (handle != JniRtpSound.INVALID_HANDLE) {
            JniRtpSound.rtpsound_close(handle);
            handle = JniRtpSound.INVALID_HANDLE;
        }
    }

    /**
     * 是否打开
     * @return
     */
    public boolean isOpen() {
        return handle != JniRtpSound.INVALID_HANDLE;
    }

    /**
     * 获取音量, 取值范围为[0,1]
     * @return
     */
    public float getVolume() {
        return JniRtpSound.rtpsound_getVolume(handle);
    }

    /**
     * 设置音量, 取值范围为[0,1]
     * @param volume
     */
    public void setVolume(float volume) {
        if (volume < 0.0) {
            volume = 0.0f;
        } else if (volume > 1.0) {
            volume = 1.0f;
        }

        JniRtpSound.rtpsound_setVolume(handle, volume);
    }


}
